using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Http;
using System.IO;
using Newtonsoft.Json;

namespace Mes.质检管理.MaterialChenck
{
	public partial class QueckChenck : Form
	{
		private const string API_URL = "/api/Inspection/GetQueryCheck";
		
		// 分页相关变量
		private int currentPage = 1;
		private int pageSize = 20;
		private int totalCount = 0;
		private int totalPages = 0;

		public QueckChenck()
		{
			InitializeComponent();
		}

		private void btnNew_Click(object sender, EventArgs e)
		{
			using (var dlg = new MaterialCheckAdd())
			{
				if (dlg.ShowDialog(this) == DialogResult.OK)
				{
					btnRefresh_Click(sender, e);
				}
			}
		}

		private void QueckChenck_Load(object sender, EventArgs e)
		{
			try
			{
				if (btnNew != null)
				{
					btnNew.Visible = true;
					btnNew.Enabled = true;
					btnNew.BringToFront();
					if (!panelTop.Controls.Contains(btnNew))
					{
						panelTop.Controls.Add(btnNew);
					}
				}
			}
			catch { }
			btnRefresh_Click(sender, e);
		}

		private void btnSearch_Click(object sender, EventArgs e)
		{
			LoadData(1);
		}

		private void btnRefresh_Click(object sender, EventArgs e)
		{
			txtInspectionNo.SkinTxt.Text = string.Empty;
			LoadData(1);
		}

		private void LoadData(int pageIndex)
		{
			try
			{
				Cursor = Cursors.WaitCursor;
				grid.Rows.Clear();

				var result = GetListFromApi(pageIndex, pageSize, txtInspectionNo.SkinTxt.Text?.Trim() ?? string.Empty);
				
				if (result?.data?.data != null)
				{
					// 更新分页信息
					totalCount = result.data.totalcount;
					totalPages = result.data.totalpcount;
					currentPage = pageIndex;
					
					// 更新分页控件状态
					UpdatePaginationControls();
					
					int seq = (pageIndex - 1) * pageSize + 1;
					foreach (var item in result.data.data)
					{
						// 开发调试信息（控制台输出，不弹窗）
						Console.WriteLine($"Item {seq}: InspectionNo={item.InspectionNo}, Id={item.id}");
						
						// 判断复检按钮显示文本
						string reinspectionText = "";
						if (item.InspectionResult == "不合格")
						{
							// 检查是否已有复检记录
							bool hasReinspection = CheckIfReinspectionExists(item.id);
							reinspectionText = hasReinspection ? "复检信息" : "复检";
						}
						
						grid.Rows.Add(
							seq++,
							item.InspectionNo,
							item.MaterialNo,
							item.MaterialName,
							item.InspectionDate.ToString("yyyy-MM-dd"),
							item.InspectionQuantity,
							item.QualifiedQuantity,
							item.UnqualifiedQuantity,
							item.Supplier,
							item.InspectionResult,
							"详情",  // colAction列显示"详情"按钮文本
							reinspectionText,  // colReinspection列，根据复检状态显示不同文本
							item.id   // colId列存储实际的ID值
						);
					}
				}
			}
			
			finally
			{
				Cursor = Cursors.Default;
			}
		}

		private void grid_CellContentClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex < 0 || e.ColumnIndex < 0)
			{
				return;
			}

			var col = grid.Columns[e.ColumnIndex];
			if (col.Name == "colAction")
			{
				// 打开详情窗体并传递基本信息与 InspectionId
				string inspectionNo = grid.Rows[e.RowIndex].Cells["colInspectionNo"].Value?.ToString();
				string inspectionDate = grid.Rows[e.RowIndex].Cells["colInspectionDate"].Value?.ToString();
				string supplier = grid.Rows[e.RowIndex].Cells["colSupplier"].Value?.ToString();
				int inspectionId = 0;
				var idCell = grid.Rows[e.RowIndex].Cells["colId"];
				if (idCell != null && idCell.Value != null)
				{
					int.TryParse(idCell.Value.ToString(), out inspectionId);
				}
				
				using (var dlg = new CheckDetial
				{
					InspectionNo = inspectionNo,
					InspectionDate = inspectionDate,
					Supplier = supplier,
					InspectionId = inspectionId
				})
				{
					dlg.ShowDialog(this);
				}
			}
			else if (col.Name == "colReinspection")
			{
				// 处理复检按钮点击事件
				string inspectionResult = grid.Rows[e.RowIndex].Cells["colInspectionResult"].Value?.ToString();
				string inspectionNo = grid.Rows[e.RowIndex].Cells["colInspectionNo"].Value?.ToString();
				string materialName = grid.Rows[e.RowIndex].Cells["colMaterialName"].Value?.ToString();
				string supplier = grid.Rows[e.RowIndex].Cells["colSupplier"].Value?.ToString();
				string inspectionDate = grid.Rows[e.RowIndex].Cells["colInspectionDate"].Value?.ToString();
				int inspectionId = 0;
				var idCell = grid.Rows[e.RowIndex].Cells["colId"];
				if (idCell != null && idCell.Value != null)
				{
					int.TryParse(idCell.Value.ToString(), out inspectionId);
				}
				
				// 检查是否已经有复检记录
				bool hasReinspection = CheckIfReinspectionExists(inspectionId);
				
				if (hasReinspection)
				{
					// 如果已有复检记录，打开复检详情页面
					OpenReinspectionDetailForm(inspectionId, inspectionNo, materialName, supplier, inspectionDate);
				}
				else if (inspectionResult == "不合格")
				{
					// 如果没有复检记录且质检结果不合格，显示复检确认对话框
					var result = MessageBox.Show(
						$"确定要对质检编号 {inspectionNo} 的原料 {materialName} 进行复检吗？",
						"复检确认",
						MessageBoxButtons.YesNo,
						MessageBoxIcon.Question
					);
					
					if (result == DialogResult.Yes)
					{
						// 跳转到复检页面
						OpenReinspectionForm(inspectionId, inspectionNo, materialName);
					}
				}
			}
		}

		private ApiResult<ApiPaging<List<QueryInspectionBasicDto>>> GetListFromApi(int index, int size, string inspectionNo)
		{
			try
			{
				// 构建完整的URL（前半部分由 HttpClientHelper 封装）
				string url = string.Format("{0}?index={1}&size={2}&InspectionNo={3}",
					HttpClientHelper.GetApiUrl("/api/Inspection/GetQueryCheck"),
					index,
					size,
					Uri.EscapeDataString(inspectionNo ?? string.Empty));
				
				// 使用HttpClient直接调用接口
				using (var httpClient = new System.Net.Http.HttpClient())
				{
					// 设置超时时间
					httpClient.Timeout = TimeSpan.FromSeconds(30);
					
					// 发送GET请求
					var response = httpClient.GetAsync(url).Result;
					
					// 检查响应状态
					if (response.IsSuccessStatusCode)
					{
						// 读取响应内容
						string json = response.Content.ReadAsStringAsync().Result;
						
						// 反序列化JSON
						return JsonConvert.DeserializeObject<ApiResult<ApiPaging<List<QueryInspectionBasicDto>>>>(json);
					}
					else
					{
						// 处理错误响应
						string errorContent = response.Content.ReadAsStringAsync().Result;
						MessageBox.Show($"API调用失败: {response.StatusCode} - {errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
						return null;
					}
				}
			}
			catch (Exception ex)
			{
				// 处理异常
				MessageBox.Show($"调用接口时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return null;
			}
		}

		#region 分页方法
		
		/// <summary>
		/// 更新分页控件状态
		/// </summary>
		private void UpdatePaginationControls()
		{
			// 更新分页信息显示
			lblPageInfo.Text = $"第 {currentPage} 页，共 {totalPages} 页，总计 {totalCount} 条记录";
			
			// 更新按钮状态
			btnFirstPage.Enabled = currentPage > 1;
			btnPrevPage.Enabled = currentPage > 1;
			btnNextPage.Enabled = currentPage < totalPages;
			btnLastPage.Enabled = currentPage < totalPages;
			
			// 更新页码输入框
			txtCurrentPage.SkinTxt.Text = currentPage.ToString();
			txtPageSize.SkinTxt.Text = pageSize.ToString();
		}
		
		/// <summary>
		/// 首页
		/// </summary>
		private void btnFirstPage_Click(object sender, EventArgs e)
		{
			if (currentPage != 1)
			{
				LoadData(1);
			}
		}
		
		/// <summary>
		/// 上一页
		/// </summary>
		private void btnPrevPage_Click(object sender, EventArgs e)
		{
			if (currentPage > 1)
			{
				LoadData(currentPage - 1);
			}
		}
		
		/// <summary>
		/// 下一页
		/// </summary>
		private void btnNextPage_Click(object sender, EventArgs e)
		{
			if (currentPage < totalPages)
			{
				LoadData(currentPage + 1);
			}
		}
		
		/// <summary>
		/// 末页
		/// </summary>
		private void btnLastPage_Click(object sender, EventArgs e)
		{
			if (currentPage != totalPages)
			{
				LoadData(totalPages);
			}
		}
		
		/// <summary>
		/// 跳转到指定页
		/// </summary>
		private void btnGoToPage_Click(object sender, EventArgs e)
		{
			if (int.TryParse(txtCurrentPage.SkinTxt.Text, out int targetPage))
			{
				if (targetPage >= 1 && targetPage <= totalPages)
				{
					LoadData(targetPage);
				}
				else
				{
					MessageBox.Show($"页码必须在 1 到 {totalPages} 之间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				}
			}
			else
			{
				MessageBox.Show("请输入有效的页码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			}
		}
		
		/// <summary>
		/// 修改每页显示数量
		/// </summary>
		private void btnChangePageSize_Click(object sender, EventArgs e)
		{
			if (int.TryParse(txtPageSize.SkinTxt.Text, out int newPageSize))
			{
				if (newPageSize >= 1 && newPageSize <= 100)
				{
					pageSize = newPageSize;
					LoadData(1); // 重新加载第一页
				}
				else
				{
					MessageBox.Show("每页显示数量必须在 1 到 100 之间", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
				}
			}
			else
			{
				MessageBox.Show("请输入有效的数量", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
			}
		}

        #endregion

        /// <summary>
        /// 打开复检页面
        /// </summary>
        /// <param name="inspectionId">质检ID</param>
        /// <param name="inspectionNo">质检编号</param>
        /// <param name="materialName">原料名称</param>
        private void OpenReinspectionForm(int inspectionId, string inspectionNo, string materialName)
        {
            try
            {
                using (var dlg = new ReinspectionCheck.ReinspectionAdd())
                {
                    // 传递质检ID给复检页面
                    dlg.InspectionId = inspectionId;
                    dlg.InspectionNo = inspectionNo;
                    dlg.MaterialName = materialName;
                    
                    if (dlg.ShowDialog(this) == DialogResult.OK)
                    {
                        // 复检添加成功后刷新列表
                        LoadData(currentPage);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开复检页面失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void OpenReinspectionDetailForm(int inspectionId, string inspectionNo, string materialName, string supplier, string inspectionDate)
        {
            try
            {
                using (var dlg = new ReinspectionCheck.ReinspectionDetail())
                {
                    dlg.InspectionId = inspectionId;
                    dlg.InspectionNo = inspectionNo;
                    dlg.MaterialName = materialName;
                    dlg.Supplier = supplier;
                    dlg.InspectionDate = inspectionDate;
                    dlg.ShowDialog(this);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开复检详情页面失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool CheckIfReinspectionExists(int inspectionId)
        {
            try
            {
                // 构建完整的URL（前半部分由 HttpClientHelper 封装）
                string url = HttpClientHelper.GetApiUrl("/api/Inspection/GetReinspectionByCheckId") + $"?CheckId={inspectionId}";
                
                // 使用HttpClient直接调用接口
                using (var httpClient = new System.Net.Http.HttpClient())
                {
                    // 设置超时时间
                    httpClient.Timeout = TimeSpan.FromSeconds(30);
                    
                    // 发送GET请求
                    var response = httpClient.GetAsync(url).Result;
                    
                    // 检查响应状态
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取响应内容
                        string json = response.Content.ReadAsStringAsync().Result;
                        
                        // 反序列化JSON
                        var result = JsonConvert.DeserializeObject<MaterialChenck.ApiResult<object>>(json);
                        return result != null && result.code == 200 && result.data != null;
                    }
                    else
                    {
                        // 如果API调用失败，默认返回false（没有复检记录）
                        return false;
                    }
                }
            }
            catch
            {
                // 如果API调用失败，默认返回false（没有复检记录）
                return false;
            }
        }
        
    }

    public class ApiResult<T>
	{
		public int code { get; set; }
		public string message { get; set; }
		public T data { get; set; }
	}

	public class ApiPaging<T>
	{
		public int totalcount { get; set; }
		public int totalpcount { get; set; }
		public T data { get; set; }
	}

	public class QueryInspectionBasicDto
	{
		public int id { get; set; }
		public string InspectionNo { get; set; }
		public string MaterialNo { get; set; }
		public string MaterialName { get; set; }
		public DateTime InspectionDate { get; set; }
		public int InspectionQuantity { get; set; }
		public int QualifiedQuantity { get; set; }
		public int UnqualifiedQuantity { get; set; }
		public string Supplier { get; set; }
		public string InspectionResult { get; set; }
		public bool del { get; set; }
	}
}
